package com.lihang.rabbit1.config;

import org.springframework.stereotype.Component;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求体过滤器
 * 将请求包装为可重复读取的请求
 */
@Component
public class RequestBodyFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) {
        // 初始化时不做任何操作
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        // 只处理HTTP请求
        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            
            // 判断是否为POST、PUT等可能带有请求体的请求
            String method = httpRequest.getMethod();
            if (isRequestWithBody(method)) {
                RequestBodyWrapper requestWrapper = new RequestBodyWrapper(httpRequest);
                ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) response);
                
                // 保存请求体到请求属性中，供拦截器使用
                requestWrapper.setAttribute("requestBody", requestWrapper.getRequestBody());
                
                // 继续过滤器链
                chain.doFilter(requestWrapper, responseWrapper);
                
                // 恢复响应内容
                responseWrapper.copyBodyToResponse();
            } else {
                // 对于GET等请求，直接处理
                chain.doFilter(request, response);
            }
        } else {
            // 非HTTP请求，直接处理
            chain.doFilter(request, response);
        }
    }
    
    @Override
    public void destroy() {
        // 销毁时不做任何操作
    }
    
    /**
     * 判断该请求方法是否可能带有请求体
     */
    private boolean isRequestWithBody(String method) {
        return "POST".equalsIgnoreCase(method) || 
               "PUT".equalsIgnoreCase(method) || 
               "PATCH".equalsIgnoreCase(method);
    }
} 